from sanic.views import HTTPMethodView
from sanic.response import text,json
import time
from processing.other_func import ProToken,Sercret_all,Serialization,Random_id,date_format
import json as jn
import re
from processing.Sql_DataFrom import ProJosn

class pluginAdd(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        pluginId = Random_id(32,"PLUGIN")
        try:
            sql = """
                insert into plugin(plugin_id,title,image,plugsDescribe,plugsType,paths,status,ctime) VALUES(%s,%s,%s,%s,%s,%s,%s,now())
            """
            db.insert(sql,(pluginId,html_data['title'],html_data['image'],html_data['plugsDescribe'],html_data['plugsType'],html_data['paths'],html_data['status'] ))
            return json({'code': 200, 'message': "添加成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/plugin/add', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)
class pluginList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        plugin_id = request.args.get('plugin_id') or ''

        try:
            sql = """
                select plugin_id,title,image,plugsDescribe,plugsType,paths,status from plugin 
            """

            if plugin_id:
                sql += f" where plugin_id='{plugin_id}' "

            sql += " ORDER BY ctime DESC "

            find_data = db.find_all(sql)

            if find_data:
                data = ProJosn(find_data,sql).to_dict(orient='records')
            else:
                data = []
            return json({'code': 200,'data':data, 'message': "请求成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/plugin/list', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)
class pluginDelete(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip

        html_data = request.json

        try:

            sql = "delete from plugin where plugin_id=%s"

            db.delete(sql, (html_data['plugin_id']))

            return json({'code': 200, 'message': "删除成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/plugin/delete', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)
class pluginUpdate(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip

        html_data = request.json

        try:

            sql = """
                        update plugin set title=%s,image=%s,plugsDescribe=%s,plugsType=%s,paths=%s,status=%s,ctime=now() where plugin_id=%s
                    """
            db.update(sql, (
                html_data['title'],
                html_data['image'],
                html_data['plugsDescribe'],
                html_data['plugsType'],
                html_data['paths'],
                html_data['status'],
                html_data['plugin_id'],  # 不能为空
            ))

            return json({'code': 200, 'message': "编辑成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/plugin/update', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)

class pluginMyPlugin(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json

        try:
            sql = """
                        select plugin_id from a_users where user_id=%s
                    """

            sql_find_plugin = """
                        select plugin_id,title,image,plugsDescribe,plugsType,paths,status from plugin 
                    """
            data = db.find_all(sql,(user_id))
            sum = 0
            if data[0][0]:
                for i in data[0][0].split(','):
                    if i:
                        if sum == 0:
                            sql_find_plugin += f" where plugin_id='{i}' "
                        else:
                            sql_find_plugin += f" or plugin_id='{i}' "
                        sum += 1

                sql_find_plugin += " ORDER BY ctime DESC "

                data = db.find_all(sql_find_plugin)
                data = ProJosn(data, sql_find_plugin).to_dict(orient='records')
            else:
                data = []



            return json({'code': 200, 'message': "请求成功!",'data':data})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/plugin/myPlugin', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)